#!/usr/bin/env node

const path = require("path")
const fs = require("fs")
const fse = require("fs-extra")
const AdmZip = require("adm-zip")
const yParser = require("yargs-parser")
const chalk = require("chalk")
const args = yParser(process.argv.slice(2))
const sourceMap = args.source === "false" ? false : true
let configJson = require("../pluginTemp/config.json")
const child_process = require("child_process");
const os = require("os");
checkPreview()
!sourceMap && console.log(chalk.yellow("plugin命令打包不含有map文件。如需要线上调试，请运行npm run plugin:dev"))

function printZip(zip) {
  let zipEntries = zip.getEntries() // an array of ZipEntry records
  zipEntries.forEach(function (zipEntry) {
    console.log(zipEntry.name || zipEntry.entryName) // outputs zip entries information
  })
}

Date.prototype.Format = function (fmt) {
  var o = {
    "M+": this.getMonth() + 1, //月份
    "d+": this.getDate(), //日
    "H+": this.getHours(), //小时
    "m+": this.getMinutes(), //分
    "s+": this.getSeconds(), //秒
    "q+": Math.floor((this.getMonth() + 3) / 3), //季度
    "S": this.getMilliseconds() //毫秒
  }
  if (/(y+)/.test(fmt)) fmt = fmt.replace(RegExp.$1, (this.getFullYear() + "").substr(4 - RegExp.$1.length))
  for (var k in o) {
    if (new RegExp("(" + k + ")").test(fmt)) {
      fmt = fmt.replace(RegExp.$1, (RegExp.$1.length == 1)
        ? (o[k])
        : (("00" + o[k]).substr(("" + o[k]).length)))
    }
  }
  return fmt
}
// 删除老的文件
let outputFiles = fs.readdirSync(path.resolve(__dirname, "../output"))
outputFiles.forEach((item) => {
  if (item.endsWith(".zip")) {
    fse.removeSync(path.resolve(__dirname, `../output/${item}`))
  }
})
fse.removeSync(path.resolve(__dirname, "../pluginTemp/js"))
fse.removeSync(path.resolve(__dirname, "../pluginTemp/media"))

// copy js

let mainFileName = "" // 主入口文件
fs.mkdirSync(path.resolve(__dirname, "../pluginTemp/js"))
fs.readdirSync(path.resolve(__dirname, "../dist/js")).map((file) => {
  if (path.extname(file) === ".js") {
    if (file.indexOf("app") > -1) {
      mainFileName = file
    }
    fs.copyFileSync(path.resolve(__dirname, `../dist/js/${file}`), path.resolve(__dirname, `../pluginTemp/js/${file}`))
  } else {
    if (sourceMap && path.extname(file) === ".map") {
      fs.copyFileSync(path.resolve(__dirname, `../dist/js/${file}`), path.resolve(__dirname, `../pluginTemp/js/${file}`))
    }
  }
})
// copy 静态文件
if (fs.existsSync(path.resolve(__dirname, "../dist/media"))) {
  fs.mkdirSync(path.resolve(__dirname, "../pluginTemp/media"))
  fs.readdirSync(path.resolve(__dirname, "../dist/media")).map((file) => {
    fs.copyFileSync(path.resolve(__dirname, `../dist/media/${file}`), path.resolve(__dirname, `../pluginTemp/media/${file}`))
  })
}


if (!mainFileName) {
  throw new Error("未写入main字段")
}
configJson.main = mainFileName

fs.writeFileSync(
  path.resolve(__dirname, "../pluginTemp/config.json"),
  JSON.stringify(configJson, null, 2),
  "utf8"
)

const requirementNumber = configJson["requirement-number"]
const requirementName = configJson["requirement-name"]
let internalPrefix = ""
requirementNumber && requirementName && (internalPrefix = `${requirementNumber}-${requirementName}-`)
let zip = new AdmZip()
zip.addLocalFolder(path.resolve(__dirname, "../pluginTemp"))
let pluginPath = path.resolve(
  __dirname,
  `../plugin-${internalPrefix}${new Date().Format("yy年MM月dd日-HH时mm分")}.zip`
)
zip.writeZip(pluginPath)

zip.writeZip(path.resolve(__dirname, `../output/${internalPrefix
  ? internalPrefix.slice(0, -1)
  : "插件包"}.zip`))
printZip(zip)
writeBaseInformation()
console.log(chalk.blue("打包完成..."))

function checkPreview() {
  const infomation = require("./information.json")
  if (infomation.onlineDevMode) {
    delete infomation.onlineDevMode
    fs.writeFileSync(
      path.resolve(__dirname, `./information.json`),
      JSON.stringify(infomation, null, 2),
      "utf8"
    )
    return
  }
  if (!fs.existsSync(path.resolve(__dirname, "../output/preview.png")) && configJson["requirement-number"]) {
    throw new Error("请将前端页面截图，并命名为preview.png放在output文件夹")
  }
}

function writeBaseInformation() {
  const execSync = child_process.execSync
  const information = require("./information.json")
  let baseInformationSet = information.baseInformationSet || {}
  let baseInfomation = {}
  let currentDeveloper = ""
  try {
    currentDeveloper = execSync("git config user.name", {"encoding": "utf8"}).replace("\n", "").replace("\r", "")
  } catch (e) {
    currentDeveloper = os.hostname()
  }
  [["nodeVersion", "node -v"], ["npmVersion", "npm -v"], ["pnpmVersion", "pnpm -v"]].forEach((item) => {
    try {
      baseInfomation[item[0]] = execSync(item[1]).toString().replace("\n", "").replace("\r", "")
    } catch (e) {
    }
  })
  baseInfomation.platform = os.arch().toString().replace("\n", "").replace("\r", "")
  baseInformationSet[currentDeveloper] = baseInfomation
  information.baseInformationSet = baseInformationSet
  fs.writeFileSync(
    path.resolve(__dirname, "./information.json"),
    JSON.stringify(information, null, 2),
    "utf8"
  )
}
